<?php

session_start();
if (!isset($_SESSION['uid']))
{
	header('Location:index.php?redirection=' . urlencode( $_SERVER['REQUEST_URI']) );
	exit;
}
include('config.php');
if(strchr($_REQUEST['id'], '_') )
{
	    header('Location:error.php?ec=20');
}
if (!isset($_REQUEST['id']) || $_REQUEST['id'] == '')
{
	header('Location:error.php?ec=2');
	exit;
}

$fileobj = new FileData($_GET['id'], $GLOBALS['connection'], $GLOBALS['database']);
$fileobj->setId($_GET['id']);
if ($fileobj->getError() != NULL || $fileobj->getStatus() > 0  || $fileobj->isArchived())
{
	header('Location:error.php?ec=2');
	exit;
}
if (!isset($_GET['submit']))
{
	draw_header('Checkout');
	draw_menu($_SESSION['uid']);
	draw_status_bar('Check Out Document');
	
?>
	
	
	<p>
	
	<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
	<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
	<input type="hidden" name="access_right" value="<?php echo $_GET['access_right'];?>">
	<input type="submit" name="submit" value="Click here"> to check out the selected document and begin downloading it to your local workstation.
	</form>
	Once the document has completed downloading, you may <a href="out.php">continue browsing</a>.
<?php
draw_footer();
}
else
{
    $realname = $fileobj->getName();
    if($_GET['access_right'] == 'modify')
    {	
        $query = "UPDATE {$GLOBALS['CONFIG']['db_prefix']}data SET status = '$_SESSION[uid]' WHERE id = '$_GET[id]'";
        $result = mysql_query($query, $GLOBALS['connection']) or die ("Error in query: $query. " . mysql_error());
    }
    $filename = $GLOBALS['CONFIG']['dataDir'] . $_GET['id'] . '.dat';

    if (file_exists($filename))
    {
        header ('Content-Type: application/octet-stream'); 
        header ('Content-Disposition: attachment; filename="' . $realname . '"'); 
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        readfile($filename); 
    }
    else
    {
        echo 'File does not exist...';
    }
}

?>
